﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace _3DWorldOfSmith
{
    class Square : GameObject
    {
        VertexPositionTexture[] vertices;

        VertexBuffer buffer;
        BasicEffect effect;

        GraphicsDevice device;

        public Square (GraphicsDevice graphics)
        {
            this.device = graphics;

            Start();
        }

        public override void SetUpVertices()
        {
            this.vertices = new VertexPositionTexture[4];
            #region Vertices
            this.vertices[0] = new VertexPositionTexture(new Vector3(position.X - size.X, position.Y + size.Y, position.Z), new Vector2(0, 0));
            this.vertices[1] = new VertexPositionTexture(new Vector3(position.X - size.X, position.Y - size.Y, position.Z), new Vector2(0, 1));
            this.vertices[2] = new VertexPositionTexture(new Vector3(position.X + size.X, position.Y + size.Y, position.Z), new Vector2(1, 0));
            this.vertices[3] = new VertexPositionTexture(new Vector3(position.X + size.X, position.Y - size.Y, position.Z), new Vector2(1, 1));
            #endregion
        }

        public override void Start()
        {
            position = new Vector3(0, 0, 0);
            rotation = new Vector3(0, 0, 0);
            size = new Vector3(1, 1, 1);

            SetUpVertices();

            this.buffer = new VertexBuffer(device, typeof(VertexPositionTexture), vertices.Length, BufferUsage.None);
            this.effect = new BasicEffect(device);
        }

        public override void Update()
        {
            SetUpVertices();

            world = Matrix.CreateRotationX(rotation.X) *
                    Matrix.CreateRotationY(rotation.Y) *
                    Matrix.CreateRotationZ(rotation.Z);
        }

        public override void Draw()
        {
            effect.World = world;
            effect.Projection = projection;
            effect.View = view;
            effect.TextureEnabled = true;
            effect.Texture = texture;

            device.SetVertexBuffer(buffer);

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                device.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleStrip, vertices, 0, 2);
            }
        }
    }
}